import React, { useEffect, useState } from "react";
// 导入Spring 组件
import { Spring, animated } from "react-spring";

import FilterMore from "../FilterMore";
import FilterPicker from "../FilterPicker";
import FilterTitle from "../FilterTitle";

import API from "../../../../utils/api";

import styles from "./index.module.css";

// 标题栏数组
const titleSelectedDefaultStatus = {
  area: false,
  mode: false,
  price: false,
  more: false,
};

// FilterOicker 默认选中值
const selectedDefaultValues = {
  area: ["area", "null"],
  mode: ["null"],
  price: ["null"],
  more: [],
};

export default function Filter(props) {
  const [titleSelectedStatus, settitleSelectedStatus] = useState(
    titleSelectedDefaultStatus
  );
  const [openType, setopenType] = useState("");
  const [filtersData, setfiltersData] = useState({});
  const [selectedValues, setselectedValues] = useState(selectedDefaultValues);

  useEffect(() => {
    const getFiltersData = async () => {
      // 获取当前定位城市id
      const { value } = JSON.parse(localStorage.getItem("zfy_city"));
      const res = await API.get(`/houses/condition?id=${value}`);
      setfiltersData(res.data.body);
    };
    getFiltersData();
  }, []);

  // 取消（隐藏）对话框
  const onCancel = (type) => {
    document.body.className = "";
    let newTitleSelectedStatus = { ...titleSelectedStatus };
    const selectedVal = selectedValues[type];
    if (
      type === "area" &&
      (selectedVal.length !== 2 || selectedVal[0] !== "area")
    ) {
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal.length !== 0) {
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }

    setopenType("");
    settitleSelectedStatus(newTitleSelectedStatus);
  };

  // 确定
  const onSave = (type, value) => {
    document.body.className = "";
    // 判断标题选中状态
    let newTitleSelectedStatus = { ...titleSelectedStatus };

    const selectedVal = value;

    if (
      type === "area" &&
      (selectedVal.length !== 2 || selectedVal[0] !== "area")
    ) {
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal.length !== 0) {
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }

    // 重构筛选值
    const newSelectedValues = {
      // ES6 语法 state.selectedValues[type] 的属性值会覆盖之前 [type] 对应的属性值
      ...selectedValues,
      [type]: value,
    };

    // 筛选条件数据
    const filters = {};
    const { area, mode, price, more } = newSelectedValues;

    // 区域
    const areaKey = area[0];
    let areaValue = "null";
    if (area.length === 3) {
      areaValue = area[2] !== "null" ? area[2] : area[1];
    }
    filters[areaKey] = areaValue;

    // 方式、租金
    filters.mode = mode[0];
    filters.price = price[0];

    // 特色
    filters.more = more.join(",");

    // 调用父组件的方法，把筛选数据传递给父组件
    props.onFilter(filters);

    // 更新状态
    setopenType("");
    settitleSelectedStatus(newTitleSelectedStatus);
    setselectedValues(newSelectedValues);
  };

  // 改变标题颜色
  const onTitleClick = (type) => {
    document.body.className = "body-fixed";
    let newTitleSelectedStatus = { ...titleSelectedStatus };

    // console.log(selectedValues);
    // 根据 selectedValues 里状态判断 哪些标题被选中
    Object.keys(titleSelectedStatus).forEach((key) => {
      if (key === type) {
        // 当前选中状态
        newTitleSelectedStatus[key] = true;
        return;
      }

      // 其他标题
      const selectedVal = selectedValues[key];
      if (
        key === "area" &&
        (selectedVal.length !== 2 || selectedVal[0] !== "area")
      ) {
        newTitleSelectedStatus[key] = true;
      } else if (key === "mode" && selectedVal[0] !== "null") {
        newTitleSelectedStatus[key] = true;
      } else if (key === "price" && selectedVal[0] !== "null") {
        newTitleSelectedStatus[key] = true;
      } else if (key === "more" && selectedVal.length !== 0) {
        newTitleSelectedStatus[key] = true;
      } else {
        newTitleSelectedStatus[key] = false;
      }
    });
    setopenType(type);
    settitleSelectedStatus(newTitleSelectedStatus);
  };

  // 渲染 FilterPicker 组件方法
  const renderFilterPicker = () => {
    const { area, subway, rentType, price } = filtersData;

    if (openType !== "area" && openType !== "mode" && openType !== "price") {
      return null;
    } else {
      let data = [];
      let cols = 1;
      let ddefaultValue = selectedValues[openType];
      switch (openType) {
        case "area":
          data = [area, subway];
          cols = 3;
          break;
        case "mode":
          data = rentType;
          break;
        case "price":
          data = price;
          break;
        default:
          break;
      }
      return (
        <FilterPicker
          key={openType}
          data={data}
          cols={cols}
          type={openType}
          ddefaultValue={ddefaultValue}
          onCancel={onCancel}
          onSave={onSave}
        />
      );
    }
  };

  // 渲染 FilterMore 组件方法
  const renderFilterMore = () => {
    //  characteristic, floor, oriented, roomType
    const { characteristic, floor, oriented, roomType } = filtersData;

    const data = { characteristic, floor, oriented, roomType };
    const defaultValues = selectedValues.more;
    if (openType === "more") {
      return (
        <FilterMore
          data={data}
          defaultValues={defaultValues}
          type={openType}
          onSave={onSave}
          onCancel={onCancel}
        />
      );
    } else {
      return null;
    }
  };

  // 渲染遮罩层
  const renderMask = () => {
    if (openType === "") {
      return null;
    } else {
      return (
        <Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
          {(props) => {
            return (
              <animated.div
                style={props}
                className={styles.mask}
                onClick={() => onCancel(openType)}
              />
            );
          }}
        </Spring>
      );
    }
  };
  return (
    <div className={styles.root}>
      {/* 遮罩层组件 */}
      {renderMask()}

      {/* 内容组件 */}
      <div className={styles.content}>
        {/* 标题栏 */}
        <FilterTitle
          titleSelectedStatus={titleSelectedStatus}
          onClick={onTitleClick}
        />

        {/* 前三个菜单对应内容 */}
        {renderFilterPicker()}

        {/* 最后一个菜单对应内容 */}
        {renderFilterMore()}
      </div>
    </div>
  );
}
